import { ref, Ref } from 'vue'
import { getSearchHot, getSearchSuggest, searchSong } from '@/apis/index'
export async function useHotSearchKeys() {
  const songList = ref([])
  const searchSuggestList = ref([])
  const showResult = ref(false)
  const hotkeys = ref([])
  const currentSearchKey = ref('')
  const historyKey: Ref<string[]> = ref(JSON.parse(localStorage.historyKey || "[]"))

  const getSuggest = async (keywords) => {
    showResult.value = false
    if (!keywords) {
      searchSuggestList.value = []
      return
    }
    const res = await getSearchSuggest({ keywords })
    searchSuggestList.value = res.result.allMatch
  }
  //获取歌曲列表
  const getSongList = async (keywords) => {
    showResult.value = true
    songList.value = []
    const res = await searchSong({ keywords })
    songList.value = res.result.songs.map((item, index) => {
      const subTitle: string = item.ar.map(i => i.name).join('、') + item.al.name
      return {
        title: item.name,
        free: true,//item.fee == 8,
        subTitle,
        isSq: item.privilege.playMaxbr >= 999000,
        id: item.id,
        url: `https://music.163.com/song/media/outer/url?id=${item.id}.mp3`
      }
    })
  }
  //搜索事件
  const search = (searchKey: string) => {
    const ind = historyKey.value.indexOf(searchKey)
    if (ind >= 0) {
      historyKey.value.splice(ind, 1)
    }
    historyKey.value.unshift(searchKey)
    localStorage.setItem('historyKey', JSON.stringify(historyKey.value))
    currentSearchKey.value = searchKey
    getSongList(searchKey)
  }
  //点击热门搜索词
  const clickKey = (key) => {
    search(key.first)
  }
  const deleteHistoryKey = (index) => {
    historyKey.value.splice(index, 1)
    localStorage.setItem('historyKey', JSON.stringify(historyKey.value))
  }

  const res = await getSearchHot()
  hotkeys.value = res.result.hots
  return {
    hotkeys,
    historyKey,
    currentSearchKey,
    songList,
    showResult,
    searchSuggestList,
    getSuggest,
    clickKey,
    search,
    deleteHistoryKey
  }
}
